package com.freejava.test_encache.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

/**
 * 点赞服务类
 */
@Service
public class LikeService {

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 点赞
     * @param id
     * @return
     */
    public boolean addLike(int id) {
        System.out.println("给id为" + id + "的评论点赞数加1");

        Long res = this.incr("comment_" + id, 1);
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 取消点赞
     * @param id
     * @return
     */
    public boolean removeLike(int id) {
        System.out.println("给id为" + id + "的评论点赞数减1");
        Long res = redisTemplate.opsForValue().decrement("comment_" + id);
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据评论ID获取点赞数据
     * @param id
     * @return
     */
    public String getLikeDataById(int id) {
        System.out.println("获取id为" + id + "的评论的点赞数");
        String result = (String) redisTemplate.opsForValue().get("comment_" + id);
        System.out.println(result);
        return result;
    }

    /**
     * 获取今日还剩可以点赞次数
     * @param ip
     * @return
     */
    public int getRestLikeForToday(String ip) {
        int currentTime = (int) redisTemplate.opsForValue().get(ip + "_limit_today");
        if (currentTime >= 10) {
            return 0;
        } else {
            return 10 - currentTime;
        }
    }


    /**
     * 针对increment方法二次封装，将key和value都进行序列化。
     * @param key
     * @param delta
     * @return
     */
    public Long incr(String key, long delta){
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return operations.increment(key, delta);
    }

}
